#!/bin/sh
#
# This shell script takes care of starting and stopping museekd.

MUSEEKD=/usr/bin/museekd
MUSETUP=/usr/bin/musetup
MUSCAN=/usr/bin/muscan
MUSOCKET=/tmp/museekd.root
PIDFILE=/var/run/museekd.pid
DBDIR=/var/museek
CONFIG=$DBDIR/museekd.xml
CHOWNSOCKET=YES

case "$1" in
  start)
	if [ ! -d $DBDIR ]; then 
		mkdir $DBDIR
	fi	
	if [ ! -f $CONFIG ]; then
		echo -n "Starting Museek Setup"
		echo
		if [ ! -d $DBDIR ]; then 
			mkdir $DBDIR
		fi
		$MUSETUP $CONFIG
		echo
	fi
	if [ -f $PIDFILE ]; then
		echo -n "Museek Daemon already running (or zombie pid file in /var/run/)"
		echo
		exit
	fi
	echo -n "Starting Museek Daemon"
	$MUSEEKD -c $CONFIG &>/dev/null &
	PID="$!"
	sleep 2
	if kill -0 $PID # pid check
	then 
 		if [ $CHOWNSOCKET = YES  ];
 		then 
			if [ -e $MUSOCKET ]; then chmod 666 $MUSOCKET
			# access the museekd socket from other users, may be a security risk on multiuser systems
			fi
		fi
		echo $PID > $PIDFILE
		echo
	else
		echo -n "Museekd isn't starting up properly. Check your Config file, \nor run 'museekd -c /var/museek/museekd.xml' for verbose messages."
		echo
	fi
	;;
  stop)
	echo -n "Stopping Museek Daemon"
	echo
	if [ -f $PIDFILE ]; then
		kill -15 $(cat $PIDFILE)  &>/dev/null
		rm $PIDFILE
	else
		echo -n "Museek Daemon not running"
		echo
		exit
	fi
	;;
  reconnect)
	if [ -f $PIDFILE ]; then
		echo -n "Attempting to reconnect Museekd to the Server" 
		kill -ALRM $(cat $PIDFILE)  &>/dev/null
		echo
	fi
  	;;
  restart)
	$0 stop
	sleep 3
	$0 start
	;;
  rescan)
	echo -n "Starting Muscan, rescanning shared files" 
	echo
	$MUSCAN -c $CONFIG -r -v
	echo
	$0 reload
	;;
  setup)
	echo -n "Starting Museek Setup"
	echo
	if [ ! -d $DBDIR ]; then 
		mkdir $DBDIR
	fi
	$MUSETUP $CONFIG
	echo
	;;
  reload)
	if [ -f $PIDFILE ]; then
		echo -n "Reloading Museek Daemon to update Shares" 
		kill -HUP $(cat $PIDFILE)
		echo
	else
		echo -n "Museek Daemon not running, can't reload shares"
		echo
	fi
	;;
  *)
    echo "usage: $0 {start|stop|restart|rescan|reconnect|setup|reload}"  
    echo -n
esac
